package com.caishi.lkx.user.api;

import cn.hutool.core.util.StrUtil;

import com.caishi.lkx.common.AdminBaseApi;
import com.caishi.lkx.common.role.Role;
import com.caishi.lkx.common.role.Roles;
import com.caishi.lkx.user.model.ActionModel;
import com.caishi.lkx.user.service.IActionService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @author by keray
 * date:2021/4/13 3:03 下午
 */
@RestController
@RequestMapping("/user/cu/auth/action")
public class ActionApi extends AdminBaseApi<IActionService, ActionModel, String> {

    @Resource
    private IActionService actionService;

    @Override
    public IActionService loadService() {
        return actionService;
    }

    @Roles(Role.maxAdmin)
    @PostMapping("/import")
    @Transactional(rollbackFor = Exception.class)
    public void adminImport(@RequestBody List<Map<String, Object>> data) {
        children(data, null);
    }

    private void children(List<Map<String, Object>> children, String parentCode) {
        for (var ch : children) {
            model(ch, parentCode);
        }
    }

    private void model(Map<String, Object> model, String parentCode) {
        var action = new ActionModel();
        action.setParentId(parentCode);
        var mate = model.get("meta");
        if (mate instanceof Map<?, ?> && ((Map<?, ?>) mate).containsKey("roles")) {
            var roles = ((Map<?, ?>) mate).get("roles");
            if (roles instanceof List<?> && !((List<?>) roles).isEmpty()) {
                var role = ((List<?>) roles).get(0);
                action.setId(role.toString());
                action.setName(((Map<?, ?>) mate).get("title").toString());
            }
        }
        if (StrUtil.isNotBlank(action.getId())) {
            if (actionService.contains(action.getId())) actionService.update(action);
            else actionService.insert(action);
        }
        var children = model.get("children");
        if (children instanceof List && !((List<?>) children).isEmpty()) {
            children((List<Map<String, Object>>) children, action.getId());
        }
    }
}
